<template>
    <div>
        <div class="flex">
            <ul class="url-list" v-if='isImageList'>
                <template v-for="item,index in existImageList">
                    <li class="el-upload-list__item-actions" @click="deleteImg(item,index)">
                        <div class="mode">
                            <i class="el-icon-delete-solid" />
                        </div>
                        <img :src="item" alt="">
                    </li>
                </template>
            </ul>
            <template v-if="isImageList">
                <el-upload ref="uploadImg" action="/" list-type="picture-card" :file-list="uploadImageList"
                    :http-request="upLoad" :on-preview="handleSuccess" :on-remove="handleRemove" :limit="allowNum"
                    :on-exceed="exceedChange" :disabled="allowNum == 0" :before-upload="quillImgBefore">
                    <i class="el-icon-plus" />
                </el-upload>
            </template>
            <template v-if="!isImageList">
                <el-upload ref="uploadImg" action="/" :http-request="upLoad" class="avatar-uploader" :show-file-list="false"
                    :before-upload="quillImgBefore">
                    <img v-if="imageurl" :src="imageurl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
            </template>
        </div>


        <!-- 图片预览 -->
        <el-dialog :visible.sync="dialogImg">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
  
<script>
export default {
    name: 'ImageListUpload',
    props: {
        // 已有的图片列表(上传图片列表时必传)
        existList: {
            type: Array,
            default: () => [],
        },
        // 已有的图片(上传单图时必传)
        existImage: {
            type: String,
            default: ''
        },
        // 可添加图片张数
        allowNumber: {
            type: Number,
            default: 6
        },
        // 组件是否可见
        isDisplay: {
            type: Boolean,
            required: true,
            default: false
        },
        // 是否多图
        isImageList: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            // 上传图片相关
            existImageList: [], // 已有图片列表
            uploadImageList: [], // 上传成功后的图片列表
            // 单图
            imageurl: '',

            // 图片预览弹窗
            dialogImageUrl: '',
            dialogImg: false,
        }
    },
    watch: {
        uploadImageList(val) {
            this.$emit('uploadSuccess', val);
        },
        imageurl(val) {
            console.log(val.toString());
            this.$emit('success', val);
        },
        existList() {
            this.existImageList = this.existList;
        },
        existImage() {
            this.imageurl = this.existImage;
        },
        isDisplay(val) {
            if (!val) {
                this.uploadImageList = [];
                this.imageurl = '';
            }
        }
    },
    computed: {
        allowNum() {
            return this.allowNumber - this.existList.length;
        }
    },
    created() {
        // 多图时
        this.existImageList = this.existList;
        // 单图时
        this.imageurl = this.existImage;
    },
    methods: {
        // 截取指定字符前/后的字符 不包含指定字符（obj：原字符串；character：指定字符；state：0前面部分1后面部分）
        getCaption(obj, character, state) {
            var index = obj.indexOf(character);
            if (state == 0) {
                obj = obj.substring(0, index);
            } else {
                obj = obj.substring(index + character.length, obj.length);
            }
            return obj;
        },
        // 图片上传前
        quillImgBefore(file) {
            const fileType = file.type
            const type = this.getCaption(fileType, '/', 0);
            if (type == 'image') {
                if (
                    fileType !== 'image/jpeg' &&
                    fileType !== 'image/png' &&
                    fileType !== 'image/gif' &&
                    fileType !== 'image/bmp'
                ) {
                    this.$message.error('请插入图片类型文件(jpg/jpeg/png)')
                    return false
                }

                //获取上传文件大小
                const isLt1M = Number(file.size / 1024 / 1024) < 1;
                if (!isLt1M) {
                    this.$msgbox({
                        title: "",
                        message: "文件大小不能超过1M，请重新上传。",
                        type: "warning",
                    });
                    return isLt1M;
                }
            }

        },
        // 上传
        upLoad(file) {
            this.$submitFile(file, (data) => {
                if (this.isImageList) {
                    this.uploadImageList.push(data);
                } else {
                    this.imageurl = data.url;
                }
            })
        },
        // 超过限制个数后返回
        exceedChange(files, fileList) {
            try {
                this.$message({
                    message: '图片最多只能上传'+ this.allowNumber +'张',
                    type: 'error'
                })
            } catch (error) {
                console.log(e)
            }
        },
        // 预览
        handleSuccess(file) {
            console.log(file);
            this.dialogImageUrl = file.url;
            this.dialogImg = true
            console.log(this.dialogImageUrl);
        },
        // 删除
        handleRemove(file, fileList) {
            if (file && file.status === "success") {
                const idx = this.uploadImageList.findIndex(item => {
                    return item.url == file.url
                })
                this.uploadImageList.splice(idx, 1)
            }

        },
        deleteImg(url,index) {
            this.existImageList = this.existImageList.filter((items,idx) => {
                return items != url||index != idx;
            })
            this.$emit('delExist', this.existImageList);
        },
    }
}
</script>
  
<style lang="scss" scoped>
// 上传图片相关（多图）
.url-list {
    padding: 0;
    margin: 0;
    display: inline-block;
    line-height: 0;

    li {
        overflow: hidden;
        background-color: #fff;
        border: 1px solid #c0ccda;
        border-radius: 6px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        width: 148px;
        height: 148px;
        margin: 0 8px 8px 0;
        display: inline-block;
        position: relative;

        &:hover {
            .mode {
                opacity: 1;
            }
        }

        .mode {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;

            cursor: default;
            text-align: center;
            color: #fff;
            opacity: 0;
            font-size: 20px;
            background-color: rgba(0, 0, 0, 0.5);
            -webkit-transition: opacity 0.3s;
            transition: opacity 0.3s;
        }

        img {
            width: 100%;
            height: 100%;
        }
    }
}

// 单图

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 100%;
    display: block;
}
</style>
  